from flask import Flask, render_template, url_for, redirect, request, flash
from flask_sqlalchemy import SQLAlchemy
import click

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://flaskweb:123456@10.0.0.16/watchlist'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = 'dsafkdsjalfdslajfldksjafld'
db = SQLAlchemy(app)

# 创建数据库命令
@app.cli.command()
def dbinit():
    """生成数据库数据."""
    db.create_all()

    name = 'admin'
    movies = [
        {'title': '阿凡达', 'year': '2009'},
        {'title': '地道战', 'year': '1956'},
        {'title': '开国大典', 'year': '1958'},
        {'title': '哪吒', 'year': '2025'},
    ]

    user = User(username=name, password='password123')
    db.session.add(user)
    for m in movies:
        movie = Movie(title=m['title'], year=m['year'])
        db.session.add(movie)

    db.session.commit()
    click.echo('Done.')

# 数据库模型
class User(db.Model):
    username = db.Column(db.String(20), primary_key=True)
    password = db.Column(db.String(20))

class Movie(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(60))
    year = db.Column(db.String(4))

# 主页路由
@app.route('/')
def index():
    user = User.query.first()  # 修复此处变量名
    movies = Movie.query.all()
    return render_template("index.html", user=user, movies=movies)

# 404 错误处理路由
@app.errorhandler(404)
def page_not_found(e):
    user = User.query.first()
    return render_template('404.html', user=user), 404

# 登录路由
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = User.query.filter_by(username=username).first()

        # 比对用户输入的密码和数据库中存储的密码
        if user and user.password == password:
            flash('Login successful!', 'success')
            return redirect(url_for('index'))  # 登录成功后重定向到index
        else:
            flash('无效的用户名和密码.', 'danger')

    return render_template('login.html')

if __name__ == '__main__':
    app.run(port=8000,host="0.0.0.0",debug=True)
